package cn.shop.admin.controller;

import cn.hutool.core.util.NumberUtil;
import cn.shop.admin.req.AppRewardReq;
import cn.shop.admin.req.ClearRuleReq;
import cn.shop.admin.service.PrizeRuleService;
import cn.shop.admin.service.PromotionsService;
import cn.shop.base.MyPage;
import cn.shop.transcation.promotionsModule.PrizeRule;
import cn.shop.transcation.promotionsModule.Promotions;
import cn.shop.utils.ApiResult;
import cn.shop.validation.Save;
import cn.shop.validation.Update;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static cn.shop.utils.constant.SystemSettingConstant.RECORD_REWARD_RATE;
import static cn.shop.utils.constant.SystemSettingConstant.WITHDRAW_REWARD_RATE;

/**
 * 奖励配置
 *
 * @author 痴
 * @since 2022-06-25 10:46:26
 */
@Validated
@RestController
@RequestMapping("/api/v1/promotions")
public class PromotionsController {

	/**
	 * 服务对象
	 */
	@Resource
	private PromotionsService promotionsService;
	@Resource
	private PrizeRuleService ruleService;

	/**
	 * 查询所有数据
	 *
	 * @param promotions 查询实体
	 * @return 所有数据
	 * @author 痴
	 * @since 2022-06-25 10:46:26
	 */
	@GetMapping("queryAll")
	public ApiResult<List<Promotions>> queryAll(Promotions promotions) {
		return ApiResult.success(promotionsService.list(new QueryWrapper<>(promotions)));
	}

	/**
	 * 分页查询所有数据
	 *
	 * @param page       分页对象
	 * @param promotions 查询实体
	 * @return 所有数据
	 * @author 痴
	 * @since 2022-06-25 10:46:26
	 */
	@GetMapping("queryByPage")
	public ApiResult<MyPage<Promotions>> queryByPage(MyPage<Promotions> page, Promotions promotions) {
		return ApiResult.success(promotionsService.page(page, new QueryWrapper<>(promotions)));
	}

	/**
	 * 通过主键查询单条数据
	 *
	 * @param key key
	 * @return 单条数据
	 * @author 痴
	 * @since 2022-06-25 10:46:26
	 */
	@GetMapping("queryOne/{key}")
	public ApiResult<AppRewardReq> selectOne(@PathVariable String key) {
		Promotions p =  promotionsService.getOne(Wrappers.lambdaQuery(Promotions.class).eq(Promotions::getKey, key));
		List<PrizeRule> rules = ruleService.lambdaQuery().eq(PrizeRule::getPid, p.getId()).orderByAsc(PrizeRule::getCreateTime).list();
		AppRewardReq req = new AppRewardReq();
		req.setContent(p.getContent());
		req.setPrizePool(p.getPrizePool());
		req.setEnable(p.getEnable());
		req.setPrizeRules(rules);
		req.setKey(p.getKey());
		req.setId(p.getId());
		return ApiResult.success(req);
	}

	/**
	 * 新增数据
	 *
	 * @param promotions 实体对象
	 * @return 新增结果
	 * @author 痴
	 * @since 2022-06-25 10:46:26
	 */
	@PostMapping("insert")
	public ApiResult<Map<String, Object>> insert(@Validated(Save.class) @RequestBody Promotions promotions) {
		return ApiResult.result(promotionsService.save(promotions));
	}

	/**
	 * 修改数据
	 *
	 * @param promotions 实体对象
	 * @return 修改结果
	 * @author 痴
	 * @since 2022-06-25 10:46:26
	 */
	@PutMapping("update")
	public ApiResult<Map<String, Object>> update(@Validated(Update.class) @RequestBody Promotions promotions) {
		return ApiResult.result(promotionsService.updateById(promotions));
	}

	/**
	 * 活动开关接口
	 *
	 * @param id 编号
	 * @return
	 */
	@PutMapping("disOrEnaPromotions")
	public ApiResult<Map<String, Object>> disOrEnaAccount(@Validated Long id) {
		LambdaUpdateWrapper<Promotions> updateWrapper = Wrappers.lambdaUpdate();
		updateWrapper.setSql("enable = not enable").eq(Promotions::getId, id);
		return ApiResult.result(promotionsService.update(updateWrapper));
	}

	/**
	 * 设置app活动奖励
	 *
	 * @param req 活动内容
	 * @return 返回结果
	 */
	@PutMapping("/appActivity")
	public ApiResult<Map<String, Object>> addActivity(@RequestBody @Validated AppRewardReq req) {
		List<PrizeRule> list = req.getPrizeRules();
		BigDecimal r_ratio = BigDecimal.ZERO, w_ratio = BigDecimal.ZERO;
		for (PrizeRule p : list) {
			if (RECORD_REWARD_RATE.equals(p.getKey())) {
				r_ratio = r_ratio.add(BigDecimal.valueOf(p.getRatio()));
			} else if (WITHDRAW_REWARD_RATE.equals(p.getKey())) {
				w_ratio = w_ratio.add(BigDecimal.valueOf(p.getRatio()));
			}
		}
		if (!NumberUtil.equals(r_ratio, BigDecimal.ZERO) && !NumberUtil.equals(r_ratio, BigDecimal.ONE)) {
			return ApiResult.fail("充值规则中奖率总和不正确（需要总和为1）");
		}
		if (!NumberUtil.equals(w_ratio, BigDecimal.ZERO) && !NumberUtil.equals(w_ratio, BigDecimal.ONE)) {
			return ApiResult.fail("提现规则中奖率总和不正确（需要总和为1）");
		}
		return ApiResult.result(promotionsService.saveAppActivity(req));
	}

	/**
	 * 清除活动规则
	 *
	 * @param req 清除条件
	 * @return 返回结果
	 */
	@PutMapping("/clearRule")
	public ApiResult<Map<String, Object>> clearRule(@Validated @RequestBody ClearRuleReq req) {
		return ApiResult.result(ruleService.lambdaUpdate()
				.in(PrizeRule::getKey, req.getKeys())
				.eq(PrizeRule::getPid, req.getId())
				.remove());
	}

	/**
	 * 删除单条数据
	 *
	 * @param id 主键
	 * @return 删除结果
	 * @author 痴
	 * @since 2022-06-25 10:46:26
	 */
	@DeleteMapping("delete/{id}")
	public ApiResult<Map<String, Object>> delete(@PathVariable Long id) {
		Promotions promotions = new Promotions();
		promotions.setId(id);
		return ApiResult.result(promotionsService.removeById(promotions));
	}

	/**
	 * 批量删除数据
	 *
	 * @param idList 主键结合
	 * @return 删除结果
	 * @author 痴
	 * @since 2022-06-25 10:46:26
	 */
	@DeleteMapping("batchDelete")
	public ApiResult<Map<String, Object>> batchDelete(@RequestParam("idList") List<Long> idList) {
		return ApiResult.result(promotionsService.batchDelete(idList, new Promotions()));
	}

}

